import { getRoleMenus } from "@/api/routes";
import {
  LayOut,
  LayoutParentView,
  LayoutLinkView,
  LayoutIframeView,
} from "@/router/constant";
import { readViews } from "@/utils/autoRead";

const pageMap = readViews();

const _import = (path) => {
  return () => Promise.resolve(pageMap[`${path}.vue`]);
};

const routesModule = {
  namespaced: true,
  state: {
    // 菜单路由
    routesList: [],
    // 需缓存路由名称
    keepAliveNames: [],
  },
  mutations: {
    // 设置路由，菜单中使用到
    setRoutesList(state, data) {
      state.routesList = data;
    },
    // 设置路由缓存（name字段）
    setCacheKeepAlive(state, data) {
      state.keepAliveNames = data;
    },
  },
  actions: {
    // 获取路由，菜单中使用到
    async getRoutesList({ commit }) {
      return new Promise((resolve) => {
        getRoleMenus().then((res) => {
          const rewriteRoutes = formatRoutes(res.data);
          commit("setRoutesList", rewriteRoutes);
          resolve(rewriteRoutes);
        });
      });
    },
  },
};

// 遍历后台传来的路由字符串，转换为组件对象
function formatRoutes(asyncRouterMap) {
  return asyncRouterMap.map((route) => {
    if (!route.meta) route.meta = {};
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = LayOut;
      } else if (route.component === "LayoutParentView") {
        route.component = LayoutParentView;
      } else if (route.meta.isLink) {
        route.component = LayoutLinkView;
      } else if (route.meta.isIframe) {
        route.component = LayoutIframeView;
      } else {
        route.component = _import(route.component);
      }
    }
    if (route.children && route.children.length) {
      route.children = formatRoutes(route.children);
    }
    return route;
  });
}

export default routesModule;
